<template>
  <div class="departments-container">
    <div class="page-header">
      <h2 class="page-title">权限管理</h2>
      <el-button
        type="primary"
        v-permission="'permission:create'"
        @click="openDialog()"
      >
        <el-icon><Plus /></el-icon>新增权限
      </el-button>
    </div>
    
    <el-card class="content-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索权限名称或代码"
          clearable
          @clear="fetchPermissions"
          @keyup.enter="fetchPermissions"
        >
          <template #append>
            <el-button @click="fetchPermissions">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
      
      <!-- 权限表格 -->
      <el-table
        :data="permissions"
        style="width: 100%"
        v-loading="loading"
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="权限名称" />
        <el-table-column label="权限代码">
          <template #default="scope">
            <el-tag :type="getPermissionTagType(scope.row.code)" effect="plain">
              {{ scope.row.code }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" />
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              v-permission="'permission:update'"
              @click="openDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              v-permission="'permission:delete'"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100]"
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑权限对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑权限' : '新增权限'"
      width="500px"
    >
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        :rules="permissionRules"
        label-width="100px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionForm.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限代码" prop="code">
          <el-input v-model="permissionForm.code" :disabled="isEdit" placeholder="请输入权限代码" />
          <div class="form-help-text" v-if="!isEdit">格式建议: 模块:操作，如 user:create</div>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="permissionForm.description"
            type="textarea"
            placeholder="请输入权限描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/user'
import { getPermissionList, createPermission, updatePermission, deletePermission, isSuccessResponse } from '../api/user'
import { formatDateTime } from '../utils/format'

// 用户信息
const userStore = useUserStore()

// 数据列表
const permissions = ref([])
const total = ref(0)
const loading = ref(false)
const page = ref(1)
const pageSize = ref(10)
const searchQuery = ref('')

// 表单数据
const dialogVisible = ref(false)
const isEdit = ref(false)
const permissionFormRef = ref(null)
const permissionForm = ref({
  name: '',
  code: '',
  description: ''
})
const permissionRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限代码', trigger: 'blur' },
    { pattern: /^[a-z0-9_]+:[a-z0-9_]+$/, message: '格式应为 module:action', trigger: 'blur' }
  ]
}

// 根据权限代码获取标签类型
const getPermissionTagType = (code) => {
  const prefix = code.split(':')[0]
  
  switch (prefix) {
    case 'user': return ''
    case 'role': return 'success'
    case 'permission': return 'warning'
    case 'rpa': return 'danger'
    case 'task': return 'info'
    case 'log': return 'warning'
    default: return ''
  }
}

// 获取权限列表
const fetchPermissions = async () => {
  try {
    loading.value = true
    const response = await getPermissionList({
      page: page.value,
      limit: pageSize.value,
      query: searchQuery.value.trim()
    })
    if (response.data && response.data.code === 200) {
      permissions.value = response.data.data.items
      total.value = response.data.data.total
    } else {
      ElMessage.error((response.data && response.data.message) || '获取权限列表失败')
    }
  } catch (error) {
    console.error('获取权限列表失败', error)
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

// 打开对话框
const openDialog = (row = null) => {
  if (row) {
    // 编辑模式
    isEdit.value = true
    permissionForm.value = {
      id: row.id,
      name: row.name,
      code: row.code,
      description: row.description || ''
    }
  } else {
    // 新增模式
    isEdit.value = false
    permissionForm.value = {
      name: '',
      code: '',
      description: ''
    }
  }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!permissionFormRef.value) return
  
  await permissionFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let response;
        if (isEdit.value) {
          // 编辑权限
          response = await updatePermission(permissionForm.value.id, permissionForm.value)
        } else {
          // 新增权限
          response = await createPermission(permissionForm.value)
        }
        
        if (response.data && response.data.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
          dialogVisible.value = false
          fetchPermissions()
        } else {
          ElMessage.error((response.data && response.data.message) || (isEdit.value ? '更新失败' : '添加失败'))
        }
      } catch (error) {
        console.error('提交权限数据失败', error)
        ElMessage.error('提交失败，请重试')
      }
    }
  })
}

// 删除权限
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除权限 ${row.name} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deletePermission(row.id)
      if (response.data && response.data.code === 200) {
        ElMessage.success('删除成功')
        fetchPermissions()
      } else {
        ElMessage.error((response.data && response.data.message) || '删除失败')
      }
    } catch (error) {
      console.error('删除权限失败', error)
      ElMessage.error('删除失败，请重试')
    }
  }).catch(() => {})
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchPermissions()
}

const handleCurrentChange = (val) => {
  page.value = val
  fetchPermissions()
}

// 监听搜索关键字变化
watch(searchQuery, (newVal, oldVal) => {
  if (newVal !== oldVal && !newVal) {
    fetchPermissions()
  }
})

// 初始化
onMounted(() => {
  fetchPermissions()
})
</script>

<style scoped>
.permissions-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
  max-width: 400px;
}

.content-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.form-help-text {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style> 